package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"go-kit/demo"
	"io"
	"io/ioutil"
	"net/http"
	"runtime"
	"time"
)

func main() {
	server()
	client()
}

func server() {
	http.HandleFunc("/add", func(writer http.ResponseWriter, request *http.Request) {
		req := demo.AddReqeust{}
		err := json.NewDecoder(request.Body).Decode(&req)
		if err != nil {
			panic(err)
		}
		defer request.Body.Close()
		_ = json.NewEncoder(writer).Encode(map[string]interface{}{
			"result": req.A + req.B,
		})
	})
	go http.ListenAndServe(":8888", nil)

	runtime.Gosched()

	client()

}

func client() {
	now := time.Now()
	count := 10000
	for x := 0; x < count; x++ {
		request()
	}
	fmt.Println(time.Now().Sub(now).Milliseconds())
}

func request() {
	reader, err := addJsonRequestParams(&demo.AddReqeust{
		A: 1,
		B: 2,
	})
	if err != nil {
		return
	}
	resp, err := http.Post("http://127.0.0.1:8888/add", "application/json", reader)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	all, err := ioutil.ReadAll(resp.Body)
	fmt.Printf("%s", all)
}

func addJsonRequestParams(params interface{}) (io.Reader, error) {
	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(params); err != nil {
		return nil, err
	}
	return ioutil.NopCloser(&buf), nil
}
